package institution

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func FindOneSchool(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) (*School, error) {
	result := new(School)
	err := result.GetCollection().FindOne(ctx, filter, opts...).Decode(result)
	if err != nil {
		return nil, err
	}
	return result, err
}

func decodeSchoolCursor(ctx context.Context, cursor *mongo.Cursor) (SchoolList *[]School, err error) {
	list := make([]School, 0)
	err = cursor.All(ctx, SchoolList)
	if err != nil {
		return nil, err
	}
	return &list, err
}

func QueryManySchool(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (result *[]School, err error) {
	cursor, err := (&School{}).GetCollection().Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}
	result, err = decodeSchoolCursor(ctx, cursor)
	return result, err
}

func (s *School) FindByID(ctx context.Context, opts ...*options.FindOneOptions) error {
	return s.FindLastOne(ctx, &bson.D{{"_id", s.ID}}, opts...)
}

// FindLastOne /* 查找单个 */
func (s *School) FindLastOne(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) error {
	_opt := make([]*options.FindOneOptions, 0)
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	_opt = append(_opt, options.FindOne().SetSort(bson.D{{"_id", -1}}))
	return s.GetCollection().FindOne(ctx, *filter, _opt...).Decode(s)
}

type SchoolList []School

// FindMany /* 查找d多个 */
func (somes *SchoolList) FindMany(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	_opt := make([]*options.FindOptions, 0)
	_opt = append(_opt, options.Find().SetSort(bson.D{{"_id", -1}}))
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	cursor, err := (&School{}).GetCollection().Find(ctx, *filter, _opt...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, somes)
}

// 条件
